import { useState, useEffect } from "react";
import { View, Text, Input, Button, ScrollView } from "@tarojs/components";
import Taro from "@tarojs/taro";
import useWeatherStore from "../../stores/weatherStore";
import "./index.scss";

const WeatherPage = () => {
  const [city, setCity] = useState("");
  const [hasInput, setHasInput] = useState(false);
  const {
    currentWeather,
    weatherForecast,
    loading,
    error,
    searchHistory,
    fetchWeather,
    clearError,
    removeFromSearchHistory,
    clearSearchHistory,
    initHistory,
  } = useWeatherStore();

  // 初始化历史记录
  useEffect(() => {
    initHistory();
  }, [initHistory]);

  // 错误提示
  useEffect(() => {
    if (error) {
      Taro.showToast({
        title: error,
        icon: "none",
        duration: 3000,
      });
      const timer = setTimeout(() => {
        clearError();
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [error, clearError]);

  const handleInput = (e) => {
    // 兼容 Taro 小程序环境和 Web 测试环境
    const value = e.detail?.value || e.target?.value || "";
    console.log("输入事件:", e); // 调试用
    console.log("获取的值:", value); // 调试用
    setCity(value);
    setHasInput(!!value.trim());
  };

  const handleSearch = () => {
    if (!city.trim()) {
      Taro.showToast({
        title: "请输入城市名称",
        icon: "none",
      });
      return;
    }
    fetchWeather(city.trim());
  };

  const handleHistoryClick = (historyCity) => {
    setCity(historyCity);
    setHasInput(true);
    fetchWeather(historyCity);
  };

  const handleClearInput = () => {
    setCity("");
    setHasInput(false);
  };

  const handleDeleteHistory = (historyCity, e) => {
    e.stopPropagation(); // 阻止冒泡，避免触发点击查询
    removeFromSearchHistory(historyCity);
    Taro.showToast({
      title: "已删除",
      icon: "success",
      duration: 1000,
    });
  };

  const handleClearAllHistory = () => {
    Taro.showModal({
      title: "确认清空",
      content: "确定要清空所有搜索历史吗？",
      success: (res) => {
        if (res.confirm) {
          clearSearchHistory();
          Taro.showToast({
            title: "已清空历史记录",
            icon: "success",
            duration: 1500,
          });
        }
      },
    });
  };

  return (
    <View className="weather-page">
      {/* 搜索区域 */}
      <View className="search-section">
        <View className="search-box">
          <Input
            className="search-input"
            value={city}
            onInput={handleInput}
            placeholder="输入城市名称，如：北京"
            placeholderClass="placeholder"
            onConfirm={handleSearch}
          />
          {/* 清除按钮 */}
          {hasInput && (
            <View className="clear-btn" onClick={handleClearInput}>
              ✕
            </View>
          )}
          <Button
            className={`search-btn ${hasInput ? "active" : "disabled"}`}
            onClick={handleSearch}
            loading={loading}
            disabled={loading || !hasInput}
          >
            {loading ? "查询中..." : "查询天气"}
          </Button>
        </View>

        {/* 搜索历史 */}
        {searchHistory.length > 0 && (
          <View className="search-history">
            <View className="history-header">
              <Text className="history-title">搜索历史</Text>
              <View className="clear-all-btn" onClick={handleClearAllHistory}>
                清空
              </View>
            </View>
            <View className="history-list">
              {searchHistory.map((item, index) => (
                <View
                  key={index}
                  className="history-item"
                  onClick={() => handleHistoryClick(item)}
                >
                  <Text className="history-text">{item}</Text>
                  <View
                    className="delete-btn"
                    onClick={(e) => handleDeleteHistory(item, e)}
                  >
                    ×
                  </View>
                </View>
              ))}
            </View>
          </View>
        )}
      </View>

      <ScrollView className="content-scroll" scrollY>
        {/* 当前天气 */}
        {currentWeather && (
          <View className="current-weather-card">
            <View className="location-section">
              <Text className="city-name">{currentWeather.city}</Text>
              <Text className="weather-icon">{currentWeather.icon}</Text>
            </View>

            <View className="temperature-section">
              <Text className="temperature">{currentWeather.temperature}°</Text>
              <Text className="weather-desc">{currentWeather.weather}</Text>
            </View>

            <View className="weather-details">
              <View className="detail-item">
                <Text className="label">湿度</Text>
                <Text className="value">{currentWeather.humidity}%</Text>
              </View>
              <View className="detail-item">
                <Text className="label">风速</Text>
                <Text className="value">{currentWeather.windpower}级</Text>
              </View>
              <View className="detail-item">
                <Text className="label">风向</Text>
                <Text className="value">{currentWeather.winddirection}</Text>
              </View>
            </View>
          </View>
        )}

        {/* 天气预报 */}
        {weatherForecast && (
          <View className="forecast-card">
            <Text className="card-title">天气预报</Text>
            <View className="forecast-list">
              {weatherForecast.casts.slice(0, 3).map((cast, index) => (
                <View key={index} className="forecast-item">
                  <Text className="day">
                    {index === 0 ? "今天" : index === 1 ? "明天" : "后天"}
                  </Text>
                  <Text className="weather-icon">{cast.icon}</Text>
                  <Text className="weather">{cast.dayweather}</Text>
                  <Text className="temperature-range">
                    {cast.nighttemp}° ~ {cast.daytemp}°
                  </Text>
                </View>
              ))}
            </View>
          </View>
        )}

        {/* 空状态 */}
        {!currentWeather && !loading && (
          <View className="empty-state">
            <Text className="empty-icon">🌤️</Text>
            <Text className="empty-text">输入城市名称查询天气</Text>
          </View>
        )}
      </ScrollView>
    </View>
  );
};

export default WeatherPage;
